package com.google.code.web;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.util.List;
import java.util.Map;

public class HttpResponse {
	private HttpURLConnection hconn;

	public int getResponseCode() throws IOException {
		return this.hconn.getResponseCode();
	}

	public String getResponseHtml() throws UnsupportedEncodingException,
			IOException {
		String str = null;
		int tryTimes  =3;
		while(tryTimes > 0){
			try {
				str = this.getResponseHtml("ISO-8859-1", "UTF-8");
				break;
			} catch (Exception e) {
				tryTimes--;
			}
		}
		return str;
	}

	public String getResponseHtml(String inEncode, String outEncode)
			throws UnsupportedEncodingException, IOException {
		Reader r = new InputStreamReader(new BufferedInputStream(
				hconn.getInputStream()), inEncode);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int b = -1;
		while (-1 != (b = r.read())) {
			baos.write((byte) b);
		}

		return new String(baos.toByteArray(), outEncode);
	}

	public String getHeaderField(String name) {
		return this.hconn.getHeaderField(name);
	}

	public Map<String, List<String>> getHeaderFields() {
		return this.hconn.getHeaderFields();
	}

	public HttpResponse(HttpURLConnection hconn) throws Exception {
		if (hconn == null)
			throw new Exception("HttpURLConnection should not be null.");
		this.hconn = hconn;
	}
}
